package com.eschool.service.impl;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.eschool.dao.SaasAdminDao;
import com.eschool.dao.UserDao;
import com.eschool.model.SaasAdmin;
import com.eschool.model.User;
import com.eschool.service.UserService;

public class UserServiceImpl implements UserService {

	@Override
	public boolean authenticateUser(User user) {
		User _user = UserDao.getUserByProperty("email", user.getEmail());

		if (_user != null)
			if ( user.getPassword().equals(_user.getPassword()) ){
				HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
				HttpSession session = request.getSession();
				
				session.setAttribute("user", _user);
				
				session.setAttribute("admin", null);

				return true;
			}
		return false;
	}


	@Override
	public boolean authenticateSaasAdmin(SaasAdmin user) {
		SaasAdmin _user = SaasAdminDao.getAdminByProperty("email", user.getEmail());
		
		if (_user != null)
			if ( user.getPassword().equals(_user.getPassword()) ){
				HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
				HttpSession session = request.getSession();
				
				System.out.print("Found");
				
				session.setAttribute("admin", _user);
				
				session.setAttribute("user", null);
				return true;
			}
		return false;
	}


	@Override
	public String logOutUser() {
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		HttpSession session = request.getSession();
		
		if ( ! (session.getAttribute("user") == null ) ) {
			session.setAttribute("user", null);
			session.invalidate();
			return "login";
		}
		
		if ( ! (session.getAttribute("admin") == null) ) {
			session.setAttribute("admin", null);
			session.invalidate();
			return "admin_login";
		}
		
		return null;
	}
}
